package com.example.fw;

import java.util.ArrayList;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import com.example.tests.PersonData;

public class PersonHelper extends HelperBase{
	
	public PersonHelper(ApplicationManager manager) {
		super(manager);
	}

	public void initPersonCreation() {
		click(By.linkText("add new"));
	}

	public void fillAddNewPersonPage(PersonData person) {
		type(By.name("firstname"), person.firstName);
		type(By.name("lastname"), person.secondName);
		type(By.name("address"), person.address1);		
		type(By.name("home"), person.homePhone);
		type(By.name("mobile"), person.mobilePhone);
		type(By.name("work"), person.workPhone);
		type(By.name("email"), person.email);
		type(By.name("email2"), person.email2);
	    selectByText(By.name("bday"), person.bday);
	    selectByText(By.name("bmonth"), person.bmonth);
	    type(By.name("byear"), person.byear);
	    selectByText(By.name("new_group"), person.group);
		type(By.name("address2"), person.address2);
		type(By.name("phone2"), person.phone2);
	}

	public void returnToHomePage() {
		click(By.linkText("home page"));
	}

	public void initPersonEditing(int index) {          
		List<WebElement> rows = driver.findElements(By.xpath("//tr[@name ='entry']"));
		List<WebElement> cells = rows.get(index).findElements(By.tagName("td"));
		cells.get(6).findElement(By.tagName("a")).click();
	}
	
	public void initPersonView(int index) {          
		List<WebElement> rows = driver.findElements(By.xpath("//tr[@name ='entry']"));
		List<WebElement> cells = rows.get(index).findElements(By.tagName("td"));
		cells.get(5).findElement(By.tagName("a")).click();
	}	

	public void submitPersonModification() {
		click(By.xpath("//input[@value='Update']"));
	}

	public void deleteCurrentPerson() {
		click(By.xpath("//input[@value='Delete']"));
	}

	public void initPersonModification() {
		click(By.name("modifiy"));		
	}

	public List<PersonData> getPersons() {
		List<PersonData> persons = new ArrayList<PersonData>();
		List<WebElement> rows = driver.findElements(By.xpath("//tr[@name ='entry']"));
		for (WebElement row : rows){
			List<WebElement> cells = row.findElements(By.tagName("td"));
			PersonData person = new PersonData();
			person.secondName = cells.get(1).getText();
			person.firstName = cells.get(2).getText();
			person.email = cells.get(3).getText();
			person.homePhone = cells.get(4).getText();
			persons.add(person);			
		}
		return persons;
	}

}
